package cn.com.czpb.client.module.actives;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.BaseFragment;
import cn.com.czpb.client.custorm.smartrefreshalayout.ClassHeader_other;
import cn.com.czpb.client.model.active.ActiveListBean;
import cn.com.czpb.client.model.active.ActiveListEntity;
import cn.com.czpb.client.module.MainActivity;
import cn.com.czpb.client.module.actives.adapter.HuodongRecycleAdapter;
import cn.com.czpb.client.module.video.utils.VideoPlayerHelper;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/12.
 */

public class HuodongFragment extends BaseFragment implements OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemChildClickListener {
    @BindView(R.id.recycler_list_id)
    RecyclerView recyclerListId;
    @BindView(R.id.swipe_id)
    SmartRefreshLayout swipeId;
    private HuodongRecycleAdapter adapter;

    private int page=1;
    private static final int pageSize=15;//
    private boolean mFlagRefresh=true;
    private LoginQuitBR br;
    public static HuodongFragment newInstance() {
        HuodongFragment huodongFragment = new HuodongFragment();
        return huodongFragment;
    }
    @Override
    public int setMyContentView() {
        return R.layout.fragment_huodong_main;
    }
    @Override
    public void initView() {
        //初始化swip
        swipeId.setRefreshHeader(new ClassHeader_other(activity));
        swipeId.setOnRefreshListener(this);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerListId.setLayoutManager(layoutManager);
        initAdapter();
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        br = new LoginQuitBR();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MainActivity.SHOW);
        filter.addAction(MainActivity.UNSHOW);
        activity.registerReceiver(br, filter);
    }
    /**
     * adapter init
     */
    private void initAdapter() {
        adapter = new HuodongRecycleAdapter(null,spu.getShowImage());
        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this,recyclerListId);
        recyclerListId.setAdapter(adapter);
    }
    @Override
    public void initData() {
        //首次进入 延迟刷新
        swipeId.postDelayed(new Runnable() {
            @Override
            public void run() {
                mFlagRefresh = true;
                showDialog_index();
                getActiveListData();
            }
        }, 200);
    }
    /**
     * 获取视频列表数据
     */
    private void getActiveListData() {
        Map<String, String> map = new HashMap();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("Page", page+"");
        map.put("PageSize", pageSize+"");
//        map.put("PageSize", pageSize+"");
        LogUtils.i("device-->" + DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService().activelist(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ActiveListEntity>() {
                    @Override
                    public void call(ActiveListEntity entity) {
                        disMissDialog_index();
                        setListData(entity.data);
                        swipeId.finishRefresh();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("异常-->"+throwable.toString());
                        adapter.loadMoreFail();
                    }
                });
    }
    public void setListData(List<ActiveListBean> list) {

        if (mFlagRefresh){
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        }else{
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }
        LogUtils.i("size-->"+adapter.getData().size());
        if (list.size()<pageSize){
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
        swipeId.setEnabled(true);


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden){
            VideoPlayerHelper.getInstance().stop();
        }
    }






    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        ActiveListBean itemBean = (ActiveListBean) adapter.getItem(position);
        switch (view.getId()){
            case R.id.rl_id:
                PageCtrl.start2HuodongDetailActivity(itemBean.getUrl(),activity);
                break;
        }
    }
    private int mCurrentCounter = 0;
    private static final int TOTAL_COUNTER = 18;
    private boolean isErr;
    private boolean mLoadMoreEndGone = false;
    @Override
    public void onLoadMoreRequested() {
        swipeId.setEnabled(false);
        mFlagRefresh=false;
        page++;
        showDialog_index();
        getActiveListData();
    }
    public class LoginQuitBR extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(MainActivity.SHOW)) {
                adapter.notifyDataSetChanged();
            } else if (action.equals(MainActivity.UNSHOW)) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        activity.unregisterReceiver(br);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
        page=1;
        mFlagRefresh = true;
        showDialog_index();
        getActiveListData();
            }
        }, 2000);
    }
}
